﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace SAP
{
    public partial class P_GenerateFile : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DateTime firstDate = DateTime.Today.AddDays(1 - DateTime.Today.Day);
                DateTime firstDateNextMonth = firstDate.AddMonths(1);
                DateTime lastDate = firstDateNextMonth.AddDays(-1);

                txtFromDate.Text = firstDate.ToString("dd/MM/yyyy");
                txtToDate.Text = lastDate.ToString("dd/MM/yyyy");

                createStatusDealer();

            }
        }

        private void createStatusDealer()
        {
            string sql = "select '-1' CardCode, 'All' CardName ";
            sql += " union all ";
            sql += " select CardCode, CardName from OCRD where CardType = 'C' and U_WareHouse is not null ";
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddl_Dealer.DataSource = ds.Tables[0];
                ddl_Dealer.DataTextField = "CardName";
                ddl_Dealer.DataValueField = "CardCode";
                ddl_Dealer.DataBind();
            }
        }
        private string FormatDate(string dateIn)
        {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");

        }

        private void loadData()
        {

  
            string sql = "select * from ( ";
            sql += " select gs.GeneralID, gs.ServiceDate, 'A' WSCType, ws.DealerCode, ws.DealerName, ";
            sql += " ws.SeqNo, ws.VIN, ws.CustomerName, ws.FailureDate, ws.Model, ws.EngineNumber,    ";
            sql += " ConditionCode, ws.RegistrationNum, gs.Status ";
            sql += " from U_GeneralService gs     ";
            sql += " left join U_WSC ws on gs.GeneralID = ws.GeneralID where gs.JobKind = '004' AND WSCType is null   ";
            sql += " and gs.Status = 5  ";
            sql += " AND gs.ServiceDate BETWEEN '" + VSM.Utils.AppConstants.ConvertToDate(txtFromDate.Text) + "' AND '" + VSM.Utils.AppConstants.ConvertToDate(txtToDate.Text) + "'";
            if (ddl_Dealer.SelectedValue != "-1")
               sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";
            sql += " union all  ";

            sql += " select GeneralID, ServiceDate, WSCType, DealerCode, DealerName, ";
            sql += " SeqNo, VIN, CustomerName, FailureDate, Model, EngineNumber, ";
            sql += " ConditionCode,  RegistrationNum, Status from ( ";
            sql += " select row_number() over(partition by gs.GeneralID order by gs.GeneralID desc) as roworder, gs.GeneralID, gs.ServiceDate, WSCType, gs.DealerCode, gs.DealerName, ";
            sql += " gs.SeqNo, det.VIN, ''CustomerName, null FailureDate, '' Model, ''EngineNumber, ";
            sql += " ''ConditionCode, '' RegistrationNum, gs.Status   ";
            sql += " from U_GeneralService gs join U_WSCBDetail det on det.GeneralID = gs.GeneralID ";
            sql += " where gs.JobKind = '004' AND WSCType = 'B' ";
            sql += " AND gs.Status = 5 ";
            sql += " AND gs.ServiceDate BETWEEN '" + VSM.Utils.AppConstants.ConvertToDate(txtFromDate.Text) + "' AND '" + VSM.Utils.AppConstants.ConvertToDate(txtToDate.Text) + "'";
            if (ddl_Dealer.SelectedValue != "-1")
                sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";
            sql += " ) tmp where roworder = 1 ";
            sql += " )A order by DealerCode ";

            Services sv = new Services();
            Session["WSC"] = sv.ExecuteQuery("DEALER", sql).Tables[0];
            grdItem.DataSource = (DataTable)Session["WSC"];
            grdItem.DataBind();
        }

        protected void btn_Filter_Click(object sender, EventArgs e)
        {
            loadData();
        }

        protected void btn_Generate_Click(object sender, EventArgs e)
        {

            string currDealerCode = "";
            int sequenceDealer = 0;
            Services sv = new Services();
            string sumarizeText = "";
            foreach (GridViewRow row in grdItem.Rows)
            {
                CheckBox cbk = (CheckBox)row.FindControl("chkChild");
                if (cbk.Checked)
                {
                    Label lbID = (Label)row.FindControl("lbGeneralID");
                    Label DealerCode = (Label)row.FindControl("lbDealerCode");
                    Label lbWSCType = (Label)row.FindControl("lbType");
                    if (currDealerCode != DealerCode.Text) {
                        string sqlSeq = "select Sequence from U_WSCSequence where DealerCode = '" + DealerCode.Text + "'";
                        DataTable dtSeq = sv.ExecuteQuery("DEALER", sqlSeq).Tables[0];
                        sequenceDealer = Int32.Parse(dtSeq.Rows[0]["Sequence"].ToString());
                        currDealerCode = DealerCode.Text;
                    }
                    sequenceDealer++;
                    if (lbWSCType.Text == "A")
                    {
                        sumarizeText += generateTextA(lbID.Text, sequenceDealer);
                    }
                    else
                    {
                        sumarizeText += generateTextB(lbID.Text, sequenceDealer);
                    }
                   
                }
            }
            txt_GeneratedText.Text = sumarizeText;
        }

        private string generateTextA(string GeneralID, int sequence)
        {
            string sql = " SELECT [WSCID],gs.[GeneralID],wsc.[RegistrationNum],wsc.[DisCode],wsc.[DisName],wsc.[DealerCode],wsc.[DealerName] ";
            sql += ",wsc.[SeqNo],[InvoiceDate],wsc.[S],wsc.[ID],wsc.[T],[DIV],[ConditionCode],[A],[B],[C],gs.[CustomerName],gs.[VIN],[FailureDate],'A' WSCType, ";
            sql += "[KD], ";
            sql += "[SoldDate],[HourMeter],[Manu],[RefCode],[M],[COM],[RatioL],[RatioP],[FCT],[Remarks],wsc.[Status], ";
            sql += "ServiceDate, Odometer, gs.Model, EngineNumber, ";
            sql += "ItemCode, ItemName, FrgnName, Quantity, Price, VAT, DiscPrcnt ";
            sql += "FROM [U_WSC] wsc join U_GeneralService gs on wsc.GeneralID = gs.GeneralID ";
            sql += "join U_GeneralServiceDetail det on det.GeneralID = gs.GeneralID ";
            sql += "where wsc.GeneralID = " + GeneralID + " AND det.Status = 0 ";

            string sqlLabour = " select PositionCode, FRTWork, Qty, Quantity, LabourCharge from U_GeneralServiceLabour where GeneralID = " + GeneralID;
            sqlLabour += " AND Status = 0 ";
            Services sv = new Services();
            DataTable dt = sv.ExecuteQuery("DEALER", sql).Tables[0];
            DataTable dtLabour = sv.ExecuteQuery("DEALER", sqlLabour).Tables[0];

            string seqNo = "0000" + sequence;
            string txtGenerated = "";
            string prefix = "EHY ";
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];

                string soldDate = "000000";
                if(dr["SoldDate"].ToString() != "")
                    soldDate = DateTime.Parse(dr["SoldDate"].ToString()).ToString("yyMMdd");
                string failureDate = DateTime.Parse(dr["FailureDate"].ToString()).ToString("yyMMdd");
                string odometer = "000000" + Double.Parse(dr["Odometer"].ToString());

                string stock = (dr["KD"].ToString() == "1" ? soldDate : "STOCK");
                prefix += dr["DealerCode"].ToString() + seqNo.Substring(seqNo.Length - 4, 4) + "A01";
                txtGenerated += prefix + dr["ID"].ToString() + dr["T"].ToString() + "\n";
                txtGenerated += prefix + "HA" + dr["VIN"].ToString() + " " + failureDate + odometer.Substring(odometer.Length - 6, 6) + " " + stock + "\n";
                txtGenerated += prefix + "HB" + dr["ConditionCode"].ToString() + dr["A"].ToString() + dr["B"].ToString() + dr["C"].ToString() + "\n";

                int iChar = 65; //A
                foreach (DataRow drLabour in dtLabour.Rows)
                {
                    string qtyLabour = "0" + Double.Parse(drLabour["Qty"].ToString());
                    txtGenerated += prefix + "L" + (char)iChar + drLabour["PositionCode"].ToString() + drLabour["FRTWork"].ToString() + qtyLabour.Substring(qtyLabour.Length - 2, 2) + "\n";
                    iChar++;
                }
                iChar = 65;//A
                foreach (DataRow drPart in dt.Rows)
                {
                    string qtyPart = "0" + Double.Parse(drPart["Quantity"].ToString());
                    txtGenerated += prefix + "P" + (char)iChar + drPart["ItemCode"].ToString() + " " + qtyPart.Substring(qtyPart.Length - 2, 2) + "\n";
                    iChar++;
                }
                
            }
            return txtGenerated;
        }

        private string generateTextB(string GeneralID, int sequence)
        {
            Services sv = new Services();
            string sql = "select gs.GeneralID, gs.DealerCode, [S], [ID], [T], ";
            sql += " bd.VIN, bd.KD, bd.RepairDate, bd.OrderNum, bd.Hour, bd.Amount ";
            sql += " from U_GeneralService gs ";
            sql += " join U_WSCBDetail bd on gs.GeneralID = bd.GeneralID";
            sql += " where gs.GeneralID = " + GeneralID;
            DataTable dt = sv.ExecuteQuery("DEALER", sql).Tables[0];
            int Page = 1;
            int Order = 1;

            if (dt.Rows.Count > 0)
            {
                string txtGenerated = "";
                string prefix = "EHY " + dt.Rows[0]["DealerCode"].ToString().Trim();
                string seqNo = "0000" + sequence;
                string pageStr = "00" + Page;
                prefix += seqNo.Substring(seqNo.Length - 4, 4) + dt.Rows[0]["S"].ToString();
                prefix += pageStr.Substring(pageStr.Length - 2, 2);
                txtGenerated = prefix + dt.Rows[0]["ID"].ToString() + dt.Rows[0]["T"].ToString() + "\n"; 

                foreach (DataRow dr in dt.Rows) {

                    string OrderStr = "00" + Order;
                    txtGenerated += prefix + OrderStr.Substring(pageStr.Length - 2, 2);
                    string repaireDate = DateTime.Parse(dr["RepairDate"].ToString()).ToString("yyMMdd");
                    txtGenerated += dr["VIN"].ToString() + " " + repaireDate + dr["OrderNum"].ToString() + "\n";

                    Order++;
                    if (Order == 25) {
                        Order = 1;
                        Page++;
                    }
                }
                return txtGenerated;
            }
            return "";
        }
  
    }
}